#!/bin/bash

RUNTYPE="$1"
SERIAL=`ioreg -l | grep IOPlatformSerialNumber | awk '{print $4}' | tr -d '"'`
NAME="$(echo `systemsetup -getcomputername | cut -d: -f2-`)"
REPORTPATH="/Library/Managed Installs/ManagedInstallReport.plist"
SUBMITURL="REPLACE_BASEURL/update"

# Application paths
PLISTBUDDY="/usr/libexec/PlistBuddy"
PERL="/usr/bin/perl"
CURL="/usr/bin/curl"
MKTEMP="/usr/bin/mktemp"
SYSTEM_PROFILER="/usr/sbin/system_profiler"

# Copy the report to a temporary file.
TMPPLIST=/tmp/`head -c10 /dev/urandom | md5`.plist
cp "$REPORTPATH" "$TMPPLIST"

# Generate a system_profiler report.
PROFILEPLIST=/tmp/`head -c10 /dev/urandom | md5`.plist
$SYSTEM_PROFILER -xml SPSoftwareDataType SPHardwareDataType > "$PROFILEPLIST"

# Merge system profiler report with munki report.
$PLISTBUDDY -c "Add :MachineInfo:SystemProfile array" "$TMPPLIST"
$PLISTBUDDY -c "Merge $PROFILEPLIST :MachineInfo:SystemProfile" "$TMPPLIST"

# Create temp file for encoded report.
TMP=`$MKTEMP -t postflight`

echo 'report=' > "$TMP";

# We need perl to urlencode the file because older versions of OSX don't have curl with --data-urlencode.
$PERL -MURI::Escape -e 'while(<>){print uri_escape($_)}' "$TMPPLIST" >> "$TMP"

# Submit to server.
$CURL --max-time 30 --silent \
    -d "runtype=$RUNTYPE" \
    -d "serial=$SERIAL" \
    -d "name=$NAME" \
    -d @"$TMP" \
    "$SUBMITURL/postflight"

# Clean up.
rm -f "$TMP" "$TMPPLIST" "$PROFILEPLIST"

exit 0
